﻿using System.Collections.Generic;
using com.yoozoo.gta.Gameplay.RTS;
using UnityEngine;
using XLua;
using Yoozoo.Gameplay.RTS.Proto;

namespace Yoozoo.Gameplay.RTS
{
    public class MarchHud : HudBase
    {
        private bool _enablePlayerNameVisible;
        private bool _marchHudLod0OtherBattleInfoActive;
        private MarchHudLod1 _marchHudLod1;
        private MarchHudLOD1Point _marchHudLod1Point;
//        private int _oldSoldierCount;
//
//        private int __soldierCount;
//        private int _soldierCount
//        {
//            set
//            {
//                __soldierCount = value;
//            }
//            get { return __soldierCount; }
//        }
        private float _timer;

        [Header("根据hashCode对MarchHUD进行偏移的比率")]
        public float offsetPercent = -0.1f;
        private float Lod0OffetPercent = 0.001f;
        public float extraOffset = 0;

//        private TroopMarch _troopMarch;
        private GameObject _lod1Point;
        // 0 不发生改变 1头像往中间 -1 头像往左边
        private int _tweenCode;
        private bool isCachAllianceCode = false;
        
#if UNITY_EDITOR
        private string lod0OriginName;        
#endif

        public override void Initialize(int team)
        {
            base.Initialize(team);
            var hudManager = ArmyManager.Instance.HudManager;

            if (Lod0 == null)
            {
                Lod0 = hudManager.GetHud(HudManager.MarchHudLod0);
            }
            _lod0Visible = Lod0.activeInHierarchy;
            MarchHudLod0 = Lod0.GetComponent<MarchHudLod0>();
            MarchHudLod0.hudRef = this;
            if (MarchEntity.isPortraitRotated)
            {
                Lod0.transform.localEulerAngles = new Vector3(45, 135, 0);
            }
            else
            {
                Lod0.transform.localEulerAngles = new Vector3(45, 45, 0);
            }
            
            #if UNITY_EDITOR
            lod0OriginName = Lod0.name;
            Lod0.name = "MarchHud " + MarchEntity.Tid.ToString();
            #endif

            var isTruck = MarchEntity.TargetCoordinateType == TargetCoordinateType.INTERCITY_TRADE_TRUCK_45;
            var isTrain = MarchEntity.TargetCoordinateType == TargetCoordinateType.TRAIN_51;
            if (MarchEntity.RtsServerInfo.isLoadLod1Hud)
            {
                if (Lod1 == null)
                {
                    if (isTruck)
                    {
                        Lod1 = hudManager.GetHud(HudManager.TradeTruckLod1);
                    }
                    else
                    {
                        Lod1 = hudManager.GetHud(HudManager.MarchHudLod1);
                    }
                }

                _lod1Visible = Lod1.activeInHierarchy;
                _marchHudLod1 = Lod1.GetComponent<MarchHudLod1>();

                if (_lod1Point == null)
                {
                    _lod1Point = hudManager.GetHud(HudManager.MarchHudLod1Point);
                }

                _marchHudLod1Point = _lod1Point.GetComponent<MarchHudLOD1Point>();
                if (isTruck)
                {
                    _marchHudLod1Point.SetTruckIcon(MarchEntity.RtsServerInfo.truckColor - 1);
                }
                else if (isTrain)
                {
                    _marchHudLod1Point.SetTrianIcon(MarchEntity.RtsServerInfo.team);
                }
                else
                {
                    _marchHudLod1Point.SetSoldierTypeIcon(MarchEntity.RtsServerInfo,MarchEntity.ClientMarchType);
                }
                _marchHudLod1Point.SetTeam(team,MarchEntity.RtsServerInfo.tid);
                if (team == (int)MarchTeam.Self && !isTruck)
                {
                    GameObject commandHeadObj;
                    if (_marchHudLod1.MainCommander == null)
                    {
                        commandHeadObj = hudManager.GetHud(HudManager.ComCommander);
                        _marchHudLod1.MainCommander = commandHeadObj.GetComponent<ComCommander>();
                        _marchHudLod1.MainCommander.SetLod1Mat();
                        commandHeadObj.transform.SetParent(Lod1.transform);
                        commandHeadObj.transform.SetAsFirstSibling();
                        _marchHudLod1.MainCommander.frame.enabled = false;
                        _marchHudLod1.MainCommander.HpBar.enabled = false;
                        _marchHudLod1.MainCommander.HpBarFlash.enabled = false;
                    }
                    else
                    {
                        commandHeadObj = _marchHudLod1.MainCommander.gameObject;
                    }
                    commandHeadObj.transform.localRotation = Quaternion.Euler(0, 0, 0);
                    commandHeadObj.transform.localScale = new Vector3(BattleUtils.UnSelectedHudScale, BattleUtils.UnSelectedHudScale, BattleUtils.UnSelectedHudScale);
                    commandHeadObj.transform.localPosition = new Vector3(0, 88f, 0);//new Vector3(0, 46f, 0);
                    _marchHudLod1.MainCommander.battleLine.SetActive(false);
                    SetLod1CommanderHeadInfo();
                    _marchHudLod1.arrow.enabled = true;
                }
                else
                {
                    _marchHudLod1.arrow.enabled = false;
                }
            }
           
            HudType = HudType.Troop;
            
            InitAlpha();
            if (MarchEntity.RtsServerInfo.Type == TargetCoordinateType.ASSEMBLY_20)
            {
                SetAllianceIcon();
            }
            if (MarchEntity.RtsServerInfo.Type == TargetCoordinateType.MARCH_3)
            {
                SetPlayerTitle();
            }
        }
        
        public void SetEntityAndTroopData(MarchEntity marchEntity, RtsServerInfo serverInfo)
        {
            MarchEntity = marchEntity;
            _heroIconList = serverInfo.heroIconList;
            _heroQualityList = serverInfo.heroQualityList;
            _rageMaxList = serverInfo.MaxRage;
        }
        public override void SetTeam(int team)
        {
           
            base.SetTeam(team);
            if (_marchHudLod1!=null)
            {
                _marchHudLod1.MainCommander?.SetTeam(team,false,false,ArmyManager.Instance.IsCustomHudMarchType(MarchEntity.ClientMarchType));
                if (MarchEntity.TargetCoordinateType == TargetCoordinateType.INTERCITY_TRADE_TRUCK_45)
                {
                    _marchHudLod1.SetCollectTeamIcon( MarchEntity.RtsServerInfo.truckColor,MarchEntity.RtsServerInfo.tid);
                }
                else
                {
                    _marchHudLod1.SetCollectTeamIcon(team,MarchEntity.RtsServerInfo.tid);
                    _marchHudLod1Point.SetTeam(team,MarchEntity.RtsServerInfo.tid);
                }
            }
            SetParkIcon(showCommanderHead);
            if (team == 0 || MarchEntity.RtsServerInfo.isAssemblyLeader && team == (int)MarchTeam.Ally)
            {
                SetHeadFactor(EHeadFactor.IsTeamSelf,true);
            }
            else
            {
                SetHeadFactor(EHeadFactor.IsTeamSelf,false);
            }
        }
        
        public override void OnCameraPosUpdated(MarchContext marchContext)
        {
            OnLodLevelChange(marchContext);

            if (_marchLodLevel < WorldEntry.MaxShowMarchLodLevel)
            {
                //UpdateLod0ScalePosition(marchContext);
            }
            else
            {
                // 更新Lod1
                UpdateLod1(marchContext);
            }
        }
       

        protected override void OnUpdateHighLod()
        {
            MarchEntity.MarchInfo.FightFrameTime = 0;
            MarchEntity.MarchInfo.ServerInbattle = false;
        }
        /// <summary>
        /// 选中
        /// </summary>
        /// <param name="value"></param>
        /// <param name="isMultySelect"></param>
        public override void SetSelected(bool value, bool isMultySelect)
        {
            commanderSelectedChange = commanderSelectedChange || _isSelected != value;
            _isSelected = value;
            if (MarchEntity.MarchInfo.IsInBattleState && !isMultySelect) //(_team == MarchHelper.TeamFriend || _team == MarchHelper.TeamEnemy) &&
            {
                if (_isSelected)
                {
                    ArmyManager.Instance.MarchManager.SelectBattleTroop(MarchEntity.MarchInfo.Uid,MarchEntity.TargetCoordinateType, BattleUtils.TransparentAlpha, _team,new Troop( MarchEntity.MarchInfo.BattleTargetId,MarchEntity.MarchInfo.attackTargetType));
                }
                else
                {
                    ArmyManager.Instance.MarchManager.SelectBattleTroop(MarchEntity.MarchInfo.Uid,MarchEntity.TargetCoordinateType, BattleUtils.OpaqueAlpha, _team, new Troop(MarchEntity.MarchInfo.TargetId,MarchEntity.MarchInfo.TargetType));
                }
            }
            if (!_isSelected)
            {
                ArmyManager.Instance.MarchManager.SelectBattleTroop(MarchEntity.MarchInfo.Uid,MarchEntity.TargetCoordinateType, BattleUtils.OpaqueAlpha, _team);
            }

            SetHeadFactor(EHeadFactor.IsSelected,value);
            //MarchHudLod0.CommanderHead?.BaseArmyInfo.SetSelect(_isSelected, MarchEntity.MarchInfo.IsInBattleState, false, true);
            commanderHead?.SetTouchAble(_isSelected);
        }

        public override void Dispose()
        {
            hasSetParent = false;
            lastMarchStatue = EMarchStatus.Uninit;
            // 释放
            var hudManager = ArmyManager.Instance.HudManager;

            #if UNITY_EDITOR
            if (Lod0)
            {
                Lod0.name = lod0OriginName;
            }
            #endif
            
            hudManager.RecoverHud(HudManager.MarchHudLod0, Lod0);
            Lod0 = null;
            if (NewYearHudLod0 != null)
            {
                hudManager.RecoverHud(HudManager.NewYearHudLod0, NewYearHudLod0);
                NewYearHudLod0 = null;
            }
            RemoveTsanTip();
            RemoveCommanderHead(true);
            MarchHudLod0.Dispose();
            MarchHudLod0 = null;
            if (_marchHudLod1 != null && _marchHudLod1.MainCommander != null)
            {
                hudManager.RecoverHud(HudManager.ComCommander, _marchHudLod1.MainCommander.gameObject);
                _marchHudLod1.MainCommander = null;
                _marchHudLod1 = null;
            }

            if (Lod1!=null)
            {
                if (MarchEntity is { TargetCoordinateType: TargetCoordinateType.INTERCITY_TRADE_TRUCK_45 })
                {
                    hudManager.RecoverHud(HudManager.TradeTruckLod1, Lod1);
                }
                else
                {
                    hudManager.RecoverHud(HudManager.MarchHudLod1, Lod1);
                }
                Lod1 = null;
                _marchHudLod1 = null;
            }

            if (_lod1Point!=null)
            {
                
       
                hudManager.RecoverHud(HudManager.MarchHudLod1Point, _lod1Point);
                _marchHudLod1Point = null;
                 _lod1Point = null;
            }

            MarchEntity = null;
            extraOffset = 0;
            lastMarchForward = default;
            
            base.Dispose();
        }

        public override void Hide()
        {
            RemoveTsanTip();
            RemoveCommanderHead(true);
            //MarchHudLod0.PlayerNameBg.gameObject.SetActive(false);
            if (_lod1Point)
            {
                _lod1Point.transform.position = invisiblePosition;
            }

            if (NewYearHudLod0)
            {
                NewYearHudLod0.transform.position = invisiblePosition;
            }

            base.Hide();
        }

        // 战斗相关效果，释放技能，被击中等等,HUD用的状态转换函数
        public override void OnUpdateMarchTypeAndStatus()
        {
            base.OnUpdateMarchTypeAndStatus();
            //死亡时头像置灰，怒气条清零
            if (MarchEntity.MarchInfo.MarchType == MarchType.DIE_5)
            {
                bool needDispose = false;
                if (commanderHead)
                {
                    commanderHead.SetGray(true);
                    commanderHead.HpAndRage.SetRageBarProgress(0);
                    commanderHead.HpAndRage.SetRageBarActive(false);
                    commanderHead.PlayDeadAni(PlayDeadAniCallBack);
                    //SetCommanderHeadLocalPosition(MarchHudLod0.CommanderHead.gameObject);
                    isPlayingDeadHudAni = true;
                }
                else
                {
                    SetIsInBattle(false);
                    if (MarchEntity.isExpeditionMarch)
                    {
                        needDispose = true;
                    }
                }

                if (_isSelected)
                {
                    ArmyManager.Instance.MarchManager.SelectBattleTroop(MarchEntity.MarchInfo.Uid,MarchEntity.TargetCoordinateType, 1f, _team);
                }

                if (needDispose)
                {
                    MarchEntity.DisposeHud();
                    return;
                }
            }

            if (MarchEntity.isExpeditionMarchMoving)
            {
                SetIsInBattle(false);
            }
            var currentMarchStatue = MarchEntity.MarchInfo.ClientMarchStatue;
            if (lastMarchStatue != currentMarchStatue)
            {
                SetLod1MarchStateIcon();
                lastMarchStatue = currentMarchStatue;
            }
            
        }

        private EMarchStatus lastMarchStatue = EMarchStatus.Uninit;

        /// <summary>
        /// 播放头像死亡动画
        /// </summary>
        private void PlayDeadAniCallBack()
        {
            isPlayingDeadHudAni = false;
            isPlayedDeadHudAni = true;
            SetIsInBattle(false);
            if (MarchEntity != null && MarchEntity.isExpeditionMarch)
            {
                MarchEntity.DisposeHud();
            }
        }

        private void SetLod1MarchStateIcon()
        {
            string name = GetMarchStateIcon(true);
            if (string.IsNullOrEmpty(name) && MarchEntity.MarchInfo.MarchType!= MarchType.HOME_0)
            {
                var marchInfo = MarchEntity.MarchInfo;
                UnityEngine.Debug.LogError(
                    $"获取行军图标失败: {marchInfo.MarchType}, {marchInfo.ClientMarchStatue}, {marchInfo.MarchStatus}");
            }
            
            if (_marchHudLod1!=null)
            {
                ArmyManager.Instance.ResourceManager.SetMarchStateIcon(name, _marchHudLod1.SelfCollectIcon);
            }
            SetParkIcon(GetHeadShowValue(EHeadShowChange.IsHeadVisible));
            if (_marchLodLevel >= WorldEntry.MaxShowMarchLodLevel)
            {
                UpdateLod1(MarchManager.Instance.marchContext);
            }
        }


        private readonly Dictionary<MarchType, string> _marchTypeIcon = new Dictionary<MarchType, string>()
        {
            {MarchType.HOME_0,""},
            {MarchType.ATTACK_1,"icon_do_1"},
            {MarchType.GARRISON_2,"icon_do_3"},
            {MarchType.COLLECT_3,"icon_do_6"},
            {MarchType.RETURN_4,"icon_do_4"},
            {MarchType.DIE_5,"icon_do_5"},
            {MarchType.DEFENCE_6,"icon_do_10"},
            {MarchType.SCOUT_7,"icon_do_10"},
            {MarchType.AID_8,"icon_do_13"},
            {MarchType.ASSEMBLY_JOIN_11,"icon_do_7"},
            {MarchType.ASSEMBLY_OUT_12,"icon_do_7"},
            {MarchType.EXPLORE_14,"icon_do_9"},
        };
        private readonly Dictionary<EMarchStatus, string> _marchStatusIcon = new Dictionary<EMarchStatus, string>()
        {
            {EMarchStatus.Uninit,"icon_do_3_2"},
            {EMarchStatus.WALK,"icon_do_2"},
            {EMarchStatus.Battle,"icon_do_1"},
            {EMarchStatus.Park,"icon_do_3"},
            {EMarchStatus.Escape,"icon_do_5"},
            {EMarchStatus.Collect,"icon_do_6"},
            // {EMarchStatue.SIEGE_FIGHT_6,"icon_do_6"},
            {EMarchStatus.InBuilding,"icon_do_13"},
            {EMarchStatus.ClientBattle,"icon_do_1"},
            {EMarchStatus.CrossingGate,"icon_do_2"},
        };
        private string GetMarchStateIcon(bool isLod1)
        {
            var marchInfo = MarchEntity.MarchInfo;

            if (marchInfo.MarchType == MarchType.DIE_5 || marchInfo.MarchType == MarchType.EXPLORE_14)
            {
                return _marchTypeIcon[marchInfo.MarchType];
            }
       
            if (marchInfo.ClientMarchStatue == EMarchStatus.WALK)
            {
                if (marchInfo.MarchType == MarchType.RETURN_4)
                {
                    return _marchTypeIcon[marchInfo.MarchType];
                }
                else
                {
                    //return string.Empty;
                    return _marchStatusIcon[marchInfo.ClientMarchStatue];
                }
            }
            // if (isLod1)
            // {
            //     if (marchInfo.MarchType == MarchType.GARRISON_2)
            //     {
            //         return "icon_do_3";
            //     }
            // }
            if (marchInfo.MarchStatus == MarchStatus.GARRISON_3)
            {
                if (marchInfo.MarchType == MarchType.AID_8)
                {
                    return _marchTypeIcon[MarchType.AID_8];
                }
            }
            
            //if (marchInfo.MarchStatus == MarchStatus.GARRISON_3 || marchInfo.MarchStatus == MarchStatus.FIGHT_2 || marchInfo.MarchStatus == MarchStatus.COLLECT_5) 
            if (marchInfo.ClientMarchStatue == EMarchStatus.Park || marchInfo.ClientMarchStatue == EMarchStatus.CrossingGate ||marchInfo.ClientMarchStatue == EMarchStatus.Battle || marchInfo.ClientMarchStatue == EMarchStatus.ClientBattle || marchInfo.ClientMarchStatue == EMarchStatus.Collect)
            {
                return _marchStatusIcon[marchInfo.ClientMarchStatue];
            }
            return _marchTypeIcon[marchInfo.MarchType];
        }

        protected override void InitDefaultTrigger()
        {
            _enablePlayerNameVisible = MarchHudLod0.PlayerNameBg.gameObject.activeInHierarchy;
        }

        protected override void SelfInit()
        {
            SetTeam(MarchEntity.RtsServerInfo.team);
        }

        protected bool hasSetParent = false;
        private Vector3 lod0Offset = Vector3.zero;
        private Vector3 lod1Offset = Vector3.zero;
        private Vector3 _lod1PointOffset = Vector3.zero;
        private Vector3 _marchHudLod1Offset = Vector3.zero;
        private Vector3 _newYearHudLod0Offset = Vector3.zero;

        private int hashCodeAbs = 0;
        protected override void InitParentScaleAndPosition()
        {
            MarchEntity.Transform.position = MarchEntity.MarchInfo.Position;
            
            //添加偏移,主要是为了解决多个物体/UI重叠在一起的问题
            var forward1 = Lod0.transform.forward;
            int hashCode = Mathf.Abs(GetHashCode());
            float offset = (hashCode) / (1.0f * int.MaxValue) * Lod0OffetPercent;
            hashCodeAbs = hashCode;
            lod0Offset = BattleFormationHelper.hudOffset + Vector3.one * offset;
            if (MarchEntity.isPortraitRotated)
            {
                lod0Offset = Quaternion.AngleAxis(90, Vector3.up) * lod0Offset;
            }
            
            if (Lod1!=null)
            {
                Lod1.transform.localScale = new Vector3(0.005f, 0.005f, 0.005f);
                _lod1Point.transform.localScale = new Vector3(0.005f, 0.005f, 0.005f);
            }
            hasSetParent = true; 
            /*添加偏移,主要是为了解决多个物体/UI重叠在一起的问题
             方案:  
                1. 获得当前物体的HashCode,有可能是负数
                2. 将HashCode除以int的最大值,保证最后结果在(0~1.0)之内
                3. 使用offsetPercent将最终的值限制在想要的范围,如(0~0.5),offsetPercent = 0.5
             */
            SetMarchHudLod1Offset();
        }

        public void SetMarchHudLod1ExtraOffset(float extraOffset)
        {
            this.extraOffset = extraOffset;
            SetMarchHudLod1Offset();
        }

        private void SetMarchHudLod1Offset()
        {
            if (hashCodeAbs == 0)
            {
                hashCodeAbs = Mathf.Abs(GetHashCode());
            }
            if (_marchHudLod1!=null)
            {
                var forward = _marchHudLod1.transform.forward;
                var offset = (hashCodeAbs) / (1.0f * int.MaxValue) * offsetPercent + extraOffset;
                _marchHudLod1Offset = forward * offset;
                UpdateFollowPos();
            }
        }

        public override void UpdateFollowPos()
        {
            if (hasSetParent)
            {
                parentPos = MarchEntity.Transform.position;
                if (Lod0 != null)
                {
                    Lod0.transform.position = parentPos + lod0Offset;
                }
                if (Lod1 != null)
                {
                    Lod1.transform.position = parentPos + lod1Offset;
                    _lod1Point.transform.position = parentPos + _lod1PointOffset;
                }

                if (_marchHudLod1 != null)
                {
                    _marchHudLod1.transform.position = parentPos + _marchHudLod1Offset;
                }
                
                if (NewYearHudLod0 != null)
                {
                    NewYearHudLod0.transform.position = parentPos + _newYearHudLod0Offset;
                }

                if (MarchEntity.TargetCoordinateType == TargetCoordinateType.INTERCITY_TRADE_TRUCK_45 && _marchHudLod1Point != null)
                {
                    var forward = MarchEntity.Forward;
                    if (lastMarchForward != forward)
                    {
                        lastMarchForward = forward;
                        var rightForward = new Vector3(1, 0, -1);
                        var angle = Vector3.Angle(rightForward, forward);
                        _marchHudLod1Point.SetIconFlipped(angle <= 90);
                    }
   
                }
            }
        }

        private Vector3 lastMarchForward = default;
        
        public override void UpdatePlayerName()
        {
            MarchHudLod0.SetNickNamePosition(true);
        }

        public void UpdateRenownName()
        {
            MarchHudLod0.SetRenownNamePosition(true);
        }

        public void ManualUpdateCommanderInfo()
        {
            UpdateHeadShow(EHeadShowChange.IsHeadVisible);
        }

        public void UpdateCommanderBattle()
        {
            UpdateHeadShow(EHeadShowChange.IsBattleState);
        }

        protected override void InitCommanderHead()
        {
            base.InitCommanderHead();
            bool isScoutMarch = (MarchEntity.MarchInfo.MarchEntity.ClientMarchType == EClientMarchType.Scout);
            bool isScureMarch = (MarchEntity.MarchInfo.MarchEntity.ClientMarchType == EClientMarchType.Rescue);
            if (isScoutMarch || isScureMarch)
            {
                SetCommanderHeadSoldierInfoInVisible();
            }
            else
            {
                SetCommanderHeadSoldierInfoVisible();
            }
        }

        /// <summary>
        /// 隐藏头像士兵信息
        /// </summary>
        private void SetCommanderHeadSoldierInfoInVisible()
        {
            //侦察部队关闭士兵数量
            baseArmyInfo?.ChangeSoldierInfoActive(false);
        }
        /// <summary>
        /// 显示头像士兵信息
        /// </summary>
        private void SetCommanderHeadSoldierInfoVisible()
        {
            baseArmyInfo?.ChangeSoldierInfoActive(true);
        }

        private void SetLod1CommanderHeadInfo()
        {
            // 主将、副将头像
            var heroIconList = MarchEntity.RtsServerInfo.heroIconList;
            // 部队有可能出现没有英雄信息的情况,如侦察
            if (heroIconList != null && heroIconList.Length >= 1)
            {
                string mainHeroIcon = heroIconList[GetCurHeroIdx()];
                // LOD1， 只设置主将头像
                var mainCommander = _marchHudLod1.MainCommander;
                if (mainCommander)
                {
                    mainCommander.SetHero(mainHeroIcon, true);
                    mainCommander.SetActive(true, true);
                    if (_heroQualityList != null && _heroQualityList.Length >= 1)
                    {
                        mainCommander.QualityBG.enabled = true;
                        mainCommander.SetQuality(_heroQualityList[0]);
                    }
                    else
                    {
                        mainCommander.QualityBG.enabled = false;
                    }
                }
            }
        }
        protected override void InitSoldierNumAndRage()
        {
            int rageMax = MarchEntity.MarchInfo.MaxRage;
            MaxRage = rageMax;
        }
        

        protected override void OnPlayerNameVisibleChanged(bool value)
        {
            MarchHudLod0.PlayerNameBg.gameObject.SetActive(value);
            MarchHudLod0.SetNickNameVisiable(value);
            MarchHudLod0.SetRenownNameVisiable(value);
            if (MarchEntity.RtsServerInfo.Type == TargetCoordinateType.ASSEMBLY_20)
            {
                MarchHudLod0.SetAllianceIconVisible(value);
            }
            else if (MarchEntity.RtsServerInfo.Type == TargetCoordinateType.MARCH_3)
            {
                MarchHudLod0.SetPlayerTitleIconVisible(value);
            }
            else
            {
                MarchHudLod0.SetAllianceIconVisible(false);
                MarchHudLod0.SetPlayerTitleIconVisible(false);
            }
            
            if (value)
            {
                UpdateNamePosition();
                UpdateRenownNamePosition();
                if (MarchHudLod0)
                {
                    MarchHudLod0.SetNickNamePosition(true);
                    MarchHudLod0.SetRenownNamePosition(true);
                }
            }
            else
            {
                
            }
          
        }
        
        protected override void HeadVisibleChanged(bool value)
        {
            base.HeadVisibleChanged(value);
            // 基于大头像的状态设置park图标
            if (commanderHead != null && !commanderHead.gameObject.activeSelf && !value)
            {
                SetParkIcon(false);
            }
            else
            {
                SetParkIcon(value);
            }
        }

        protected override void OnBattleStyleToNormalStyle()
        {
            UpdateNamePosition();
            UpdateRenownNamePosition();
        }

        private void UpdateNamePosition()
        {
            MarchHudLod0.PlayerNameBg.transform.localPosition = new Vector3(0, -36f, 0);
        }
        
        private void UpdateRenownNamePosition()
        {
            MarchHudLod0.RenownNameBg.transform.localPosition = new Vector3(0, -10f, 0);
        }
        
        private bool enableParked = false;
        private void SetParkIcon(bool showHead)
        {
            if (showHead)
            {
                MarchHudLod0.StateIcon.enabled = false;
                MarchHudLod0.StateIconBg.enabled = false;
//                if (MarchHudLod0.StateSleepTran!=null)
//                {
//                    MarchHudLod0.StateSleepTran.localScale = Vector3.zero;
//                }
                enableParked = false;
                return;
            }

            // 1. Park图标显示：我方部队、状态是Park、不是守城部队, 非选中状态,被击溃（与ROK保持一致）
            bool enablePark = _team == MarchHelper.TeamSelf && MarchEntity.MarchInfo.ClientMarchStatue == EMarchStatus.Park && //MarchEntity.MarchInfo.MarchStatus == MarchStatus.GARRISON_3 &&
                !MarchEntity.RtsServerInfo.DefenceTroop && MarchEntity.MarchInfo.MarchType != MarchType.DIE_5 && MarchEntity.RtsServerInfo.assemblyId == 0 && MarchEntity.MarchInfo.MarchType != MarchType.RESCUE_9;// && MarchEntity.MarchInfo.ClientMarchStatue == EMarchStatus.InBuilding || MarchEntity.MarchInfo.MarchType == MarchType.DIE_5;

            // 2023.11.10科斯新需求，去掉驻扎图标,原因是采矿图标的偏移掉低了，由于用的是同一个组件，驻扎图标会和名字重叠
            enablePark = false;
            // 6. 采集状态 并且 非战斗状态 显示采集图标
            // bool enableCollect = GetFactorValue(EHeadFactor.IsCollecting);

            bool enableEscape = GetFactorValue(EHeadFactor.IsEscaping);

            bool isArena = MarchEntity.isArenaMarch;
            bool visible = (enablePark || enableEscape) && !isArena;
            //visible = MarchEntity.MarchInfo.ClientMarchStatue == EMarchStatus.Park && visible;
            MarchHudLod0.StateIcon.enabled = visible;
            MarchHudLod0.StateIconBg.enabled = visible;
            //if (visible != _marchHudLod0CollectBgEnabled)
            {
                if (visible)
                {
                    
                        var icon = GetMarchStateIcon(false);
                        ArmyManager.Instance.ResourceManager.SetMarchStateIcon(icon, MarchHudLod0.StateIcon);
//                    if (MarchHudLod0.StateSleepTran!=null)
//                    {
//                        if (enablePark)
//                        {
//                            MarchHudLod0.StateSleepTran.localScale = Vector3.one;
//                        }
//                        else
//                        {
//                            MarchHudLod0.StateSleepTran.localScale = Vector3.zero;
//                        }
//                    }
                    
                }
                else
                {
//                    if (MarchHudLod0.StateSleepTran!=null)
//                    {
//                        MarchHudLod0.StateSleepTran.localScale = Vector3.zero;
//                    }
                }
            }


        }

        private void UpdateLod1(MarchContext context)
        {
            
            
            if (_marchHudLod1 == null)
            {
                return;
            }
            if (context.LodLevel >= WorldEntry.MaxShowMarchLodLevel + 1)
            {
                if (_marchHudLod1Point.isActiveAndEnabled)
                {
                    _marchHudLod1Point.SetActive(false);
                }
            }
            else
            {
                if (!_marchHudLod1Point.isActiveAndEnabled)
                {
                    _marchHudLod1Point.SetActive(true);
                }
            }
            bool isCollecting = MarchEntity.MarchInfo.ClientMarchStatue == EMarchStatus.Collect;
            bool isBuilding = MarchEntity.MarchInfo.ClientMarchStatue == EMarchStatus.InBuilding;
            bool isSiegeAndEmpty = MarchEntity.MarchInfo.SoldierCount == 0 &&
                                   MarchEntity.MarchInfo.ClientMarchStatue == EMarchStatus.SIEGE_FIGHT;
            if (_team == MarchHelper.TeamEnemy || _team == MarchHelper.TeamOther)
            {
                // 敌方部队，不显示绿点的背景，LOD == 3时显示绿点，LOD > 3时，不显示绿点
                _marchHudLod1.SelfCollectIcon.enabled = false;
                _marchHudLod1.MainCommander?.SetActive(false);
                if (isCollecting)
                {
                    if (context.LodLevel >= WorldEntry.MaxShowMarchLodLevel && context.LodLevel < WorldEntry.MaxShowMarchLodLevel + 1)
                    {
                        _marchHudLod1.GreenPointBg.enabled = true;
                        _marchHudLod1Point.SetTeamIconVisible(false);
                        _marchHudLod1.SetOtherCollectIconEnable(true);
                    }
                    else
                    {
                        _marchHudLod1.GreenPointBg.enabled = false;
                        _marchHudLod1Point.SetTeamIconVisible(false);
                        _marchHudLod1.SetOtherCollectIconEnable(false);
                    }
                    
                }
                else
                {
                    _marchHudLod1.GreenPointBg.enabled = false;
                    _marchHudLod1Point.SetTeamIconVisible(!isBuilding && !isSiegeAndEmpty);
                    _marchHudLod1.SetOtherCollectIconEnable(false);
                }
            }
            else
            {
                // 我方或者友军，显示绿点背景，显示绿点，只有在采集状态并且LOD == 2时不显示绿点
                var visible = !isCollecting && (context.LodLevel >= WorldEntry.MaxShowMarchLodLevel) && !isBuilding;
                _marchHudLod1Point.SetTeamIconVisible(visible);
                _marchHudLod1.SetOtherCollectIconEnable(isCollecting && _team == MarchHelper.TeamFriend && context.LodLevel >= WorldEntry.MaxShowMarchLodLevel && context.LodLevel < WorldEntry.MaxShowMarchLodLevel + 1);
                _marchHudLod1.GreenPointBg.enabled = isCollecting && _team == MarchHelper.TeamFriend && context.LodLevel >= WorldEntry.MaxShowMarchLodLevel && context.LodLevel < WorldEntry.MaxShowMarchLodLevel + 1;
                if (_team == MarchHelper.TeamFriend)
                {
                    _marchHudLod1.MainCommander?.SetActive(false);
                }
                else
                {
                    _marchHudLod1.MainCommander?.SetActive(true);
                    _marchHudLod1Point.SetActive(true);
                }

                _marchHudLod1.SelfCollectIcon.enabled = _team == MarchHelper.TeamSelf;
            }

            var isTruck = MarchEntity.TargetCoordinateType == TargetCoordinateType.INTERCITY_TRADE_TRUCK_45;
            _marchHudLod1Point.SetTeamIconVisible(!(isCollecting || isBuilding || isSiegeAndEmpty) && !isTruck);
            if (isTruck)
            {
                _marchHudLod1Point.SetSoldierTypeIconVisible(true);
            }
        }
        protected override void OnLod1ScaleChanged(MarchContext marchContext)
        {
            if (Lod1 == null)
            {
                return;
            }
            base.SetHudLodScale(LodHudType.LodHighMarchHud, Lod1, marchContext);
            base.SetHudLodScale(LodHudType.LodHighMarchHudPoint, _lod1Point, marchContext);
        }

        protected override void OnLod0ScaleChanged(MarchContext marchContext)
        {
            base.SetHudLodScale(LodHudType.LodLowArmyInfo,Lod0, marchContext);
        }

        public override void UpdateHpToRealValue(bool forceFresh = false)
        {
            base.UpdateHpToRealValue(forceFresh);
            var soldierCount = MarchEntity.MarchInfo.SoldierCount;
            if (MarchEntity != null && MarchEntity.MarchInfo != null && MarchEntity.MarchInfo.ClientMarchStatue == EMarchStatus.SIEGE_FIGHT && soldierCount == 0)
            {
                _marchHudLod1Point?.SetTeamIconVisible(false);
            }
        }

        /// <summary>
        /// 沙盒的LOD切换后，切换相应的LOD物件
        /// </summary>
        /// <param name="newMarchLodLevel"></param>
        private void OnLodLevelChange(MarchContext marchContext)
        {
            // LOD == 0: None
            // LOD <  3: LOD0
            // LOD == 3: LOD1
            int newMarchLodLevel = marchContext.LodLevel;
            if (_marchLodLevel != newMarchLodLevel)
            {
                _marchLodLevel = newMarchLodLevel;
                bool isLod0Visible = _marchLodLevel < WorldEntry.MaxShowMarchLodLevel;
                bool isLod1Visible = _marchLodLevel >= WorldEntry.MaxShowMarchLodLevel;

                if (_lod0Visible != isLod0Visible)
                {
                    if (!isLod0Visible)
                    {
                        Lod0.transform.localScale = Vector3.zero;
                    }
                    else
                    {
                        SetHudLodScale(LodHudType.LodLowArmyInfo, Lod0, marchContext);
                    }

                    if (isLod0Visible)
                    {
//                        MarchHudLod0?.SetNickNameVisiable(GetHeadShowValue(EHeadShowChange.IsPlayerNameVisible));
                        UpdateHeadShow(EHeadShowChange.IsPlayerNameVisible,true);
                    }
                    else
                    {
                        MarchHudLod0?.SetRenownNameVisiable(false);
                        MarchHudLod0?.SetNickNameVisiable(false);
                    }
                    _lod0Visible = isLod0Visible;
                }

                if (Lod1!=null)
                {
                    if (_lod1Visible != isLod1Visible)
                    {
                        if (!isLod1Visible)
                        {
                            Lod1.transform.localScale = Vector3.zero;
                            _lod1Point.transform.localScale = Vector3.zero;
                        }
                        else
                        {
                            SetHudLodScale(LodHudType.LodHighMarchHud, Lod1, marchContext);
                            SetHudLodScale(LodHudType.LodHighMarchHudPoint, _lod1Point, marchContext);
                        }
                        _lod1Visible = isLod1Visible;
                    } 
                }
                
            }
        }
        private bool _lod1Visible = false;
        private bool _lod0Visible = false;
        private bool IsShowSoldierCount()
        {
            return MarchEntity.ClientMarchType != EClientMarchType.Scout;
        }
        
        public void SetAllianceIcon()
        {
            MarchHudLod0.SetLogo(MarchEntity.RtsServerInfo);
        }
        
        public void SetPlayerTitle()
        {
            MarchHudLod0.SetPlayerTitle(MarchEntity.RtsServerInfo);
        }
     
        public override void ForceShowSelectedUI(bool isSelected,bool isBattleStyle)
        {
            _forceShowHud = isSelected;
            _isBattleStyle = isBattleStyle;
            SetHeadFactor(EHeadFactor.IsForceShow,isSelected);
            SetHeadFactor(EHeadFactor.IsBattleStyle,isBattleStyle);
        }

        protected void ActiveLod1Point(bool bIsActive)
        {
            _lod1Point?.SetActive(bIsActive);
        }

        public void SetKillTip(int killNum, string killTip)
        {
            MarchHudLod0.SetKillTip(killNum, killTip);
        }

        public void SetNewYearHudArgs(float cdTime, string iconPath, LuaFunction luaCallback)
        {
            if (NewYearHudLod0)
            {
                var hudComp = NewYearHudLod0.GetComponent<NewYearHudLod0>();
                hudComp.SetClickCDTime(cdTime);
                hudComp.SetClickCallback(luaCallback);
                hudComp.SetIconImagePath(iconPath);
            }
        }
    }
}
